﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Compiled_Tests;
using LEET.CommonInterfaces.TestControls;
using Compiled_Tests.RuleBase;

namespace Compiled_Tests
{
    public class ErrorReportingController
    {
        Stack<KeyValuePair<String, int>> EmbedStack = new Stack<KeyValuePair<string, int>>();

        String currentScript = null;
        int currentLine = -1;

        public void OnTestStarted(ITestScript script)
        {
            if (currentScript != null)
            {
                EmbedStack.Push(new KeyValuePair<string, int>(currentScript, ++currentLine));
            }
            currentScript = script.GetType().ToString();
            currentLine = 0;
        }

        public void OnTestFinished()
        {
            if (EmbedStack.Count == 0)
            {
                currentScript = "";
                currentLine = -1;
            }
            else
            {
                KeyValuePair<String, int> popped = EmbedStack.Pop();
                currentScript = popped.Key;
                currentLine = popped.Value;
            }
        }

        public void OnActionTaken()
        {
            currentLine++;
        }

        public void OnSignalRecieved(ScriptSignal signal)
        {
            currentLine++;
        }

        public void OnErrorRecieved(Exception e)
        {
            EmbedStack.Push(new KeyValuePair<string, int>(currentScript, ++currentLine));

            StringBuilder buf = new StringBuilder();
            buf.Append("\r\n");
            while (EmbedStack.Count > 0)
            {
                KeyValuePair<String, int> popped = EmbedStack.Pop();
                buf.Append("\t at ").Append(popped.Key).Append(" on line: ").Append(popped.Value).Append("\r\n");
            }
            buf.Append("\r\n====================================\r\n");

            Exception temp = e;
            while (temp != null)
            {
                buf.Append(temp.StackTrace).Append("\r\n caused by: " + temp.Message + "\r\n");
                temp = temp.InnerException;
            }

            throw new Exception(e.Message + buf.ToString());
        }
        public void OnRuleBaseRecieved(IRuleBase rb)
        {
            currentLine++;
        }
        public void OnProcessRecieved(IProcess proc)
        {
            currentLine++;
        }
    }
}
